package views;


import android.app.Dialog;
import android.bluetooth.BluetoothClass;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.drinkdevice.AddSelectGoodsActivity;
import com.example.administrator.drinkdevice.MainActivity;
import com.example.administrator.drinkdevice.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.URL;

import Const.PublicDefine;
import DataAccess.DeviceDataAccess;
import Entity.ActivityResult;
import Helper.Log;
import Interface.IAsynCallBackListener;

public class Dialog_GoodsSetting_AddGoods {
    public Context context;
    private Dialog dialog;
    private Button cancelBtn;
    private Button okBtn;
    private TextView name;
    private TextView code;
    private TextView price;
    private ImageView img;
    private TextView selectGoodsBtn;

    private AutoCompleteTextView autoText;
    private String[] autoArray = new String[]{};
    private JSONArray goodsList = new JSONArray();
    private JSONObject selectGoods = null;

    public Dialog_GoodsSetting_AddGoods(final Context context, final IAsynCallBackListener callBack) {
        try {
            dialog = new Dialog(context);
            dialog.show();
            dialog.setCancelable(false);
            Window window = dialog.getWindow();
            window.setGravity(Gravity.CENTER);
            window.setContentView(R.layout.dialog_goodssetting_addgoods);
            window.setDimAmount(0);
            WindowManager.LayoutParams params = window.getAttributes();
            // 去除四角黑色背景
            window.setBackgroundDrawable(new BitmapDrawable());
            // 设置周围的暗色系数
            params.dimAmount = 0.5f;
            window.setAttributes(params);

            autoText = dialog.findViewById(R.id.autoText);
            name = dialog.findViewById(R.id.name);
            code = dialog.findViewById(R.id.code);
            price = dialog.findViewById(R.id.price);
            img = dialog.findViewById(R.id.img);
            okBtn = dialog.findViewById(R.id.addGoodsOk);
            cancelBtn = dialog.findViewById(R.id.addGoodsCancel);
            selectGoodsBtn = dialog.findViewById(R.id.selectGoodsBtn);


            //获取卖品列表
            PublicDefine.webService.getBarList(new IAsynCallBackListener() {
                @Override
                public void onFinish(Object sender, Object data) {
                    final String resStr = (String) data;
                    Message msg = new Message();
                    msg.obj = new IAsynCallBackListener() {
                        @Override
                        public void onFinish(Object sender, Object data) {
                            try {
                                JSONObject res = new JSONObject(resStr);
                                if (!res.getBoolean("success")) {
                                    throw new Exception(res.getString("message"));
                                }
                                JSONObject resData = res.getJSONObject("result");
                                goodsList = resData.getJSONArray("records");

                                autoArray = new String[goodsList.length()];

                                for (int i = 0; i < goodsList.length(); i++) {
                                    JSONObject goodsInfo = goodsList.getJSONObject(i);
                                    autoArray[i] = goodsInfo.getString("goodsName") + "--" + goodsInfo.getString("goodsCode");
                                }

                                //创建适配器
                                //使用Android自带的简单布局
                                ArrayAdapter<String> aa = new ArrayAdapter<String>(context, R.layout.dropdown_stytle, autoArray);
                                autoText.setAdapter(aa);
                                autoText.setThreshold(1);

                            } catch (Exception e) {
                                e.printStackTrace();
                                callBack.onError(null, e);
                            }
                        }

                        @Override
                        public void onError(Object sender, Exception e) {

                        }
                    };
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onError(Object sender, Exception e) {
                    callBack.onError(sender, e);
                }
            });

            autoText.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    autoText.showDropDown();//显示下拉列表
                    return false;
                }
            });

            //选择商品回调
            autoText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    try {
                        String selectStr = (String) parent.getItemAtPosition(position);
                        String[] selectStrs = selectStr.split("--");
                        for (int i = 0; i < goodsList.length(); i++) {
                            JSONObject goodsInfo = goodsList.getJSONObject(i);
                            if (goodsInfo.getString("goodsName").equals(selectStrs[0])
                                    && goodsInfo.getString("goodsCode").equals(selectStrs[1])) {
                                selectGoods = goodsInfo;
                                break;
                            }
                        }
                        name.setText(selectGoods.getString("goodsName"));
                        code.setText(selectGoods.getString("goodsCode"));
                        price.setText(new BigDecimal(selectGoods.getDouble("goodsPrice")).setScale(2, BigDecimal.ROUND_HALF_UP) + "");
                        setWebImg(selectGoods.getString("goodsImageXl"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        callBack.onError(null, e);
                    }
                }
            });

            //返回回调
            cancelBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            //确定回调
            okBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callBack.onFinish(null, selectGoods);
                }
            });

            selectGoodsBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((MainActivity) context).StartActivityForResult(AddSelectGoodsActivity.class, new IAsynCallBackListener() {
                        @Override
                        public void onFinish(Object sender, Object data) {
                            try {
                                ActivityResult res = (ActivityResult) data;
                                if (res.getResultCode() == 1) {
                                    JSONObject goodsInfo = new JSONObject(res.getData().getStringExtra("goodsInfo"));
                                    selectGoods = goodsInfo;
                                    autoText.setText(selectGoods.getString("goodsName") + "--" + selectGoods.getString("goodsCode"));
                                    name.setText(selectGoods.getString("goodsName"));
                                    code.setText(selectGoods.getString("goodsCode"));
                                    price.setText(new BigDecimal(selectGoods.getDouble("goodsPrice")).setScale(2, BigDecimal.ROUND_HALF_UP) + "");
                                    setWebImg(selectGoods.getString("goodsImageXl"));
                                }
                            } catch (Exception e) {
                                StringWriter sw = new StringWriter();
                                e.printStackTrace(new PrintWriter(sw, true));
                                Log.write("Exception", sw.toString());
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Object sender, Exception e) {

                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            callBack.onError(null, e);
        }
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof IAsynCallBackListener) {
                ((IAsynCallBackListener) msg.obj).onFinish("", msg.arg1);
            }
        }
    };

    private void setWebImg(String path) throws Exception {
        try {
            if (path == null || path.equals("")) {
                return;
            }
            new DownloadImageTask().execute(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {

        protected Drawable doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        protected void onPostExecute(Drawable result) {

            if (result != null) {
                img.setImageDrawable(result);
            }
        }
    }

    private Drawable loadImageFromNetwork(String imageUrl) {
        Drawable drawable = null;
        try {
            // 可以在这里通过文件名来判断，是否本地有此图片
            drawable = Drawable.createFromStream(
                    new URL(imageUrl).openStream(), "image.jpg");
        } catch (IOException e) {
            Log.write("test", e.getMessage());
        }
        if (drawable == null) {
            Log.d("test", "null drawable");
        } else {
            Log.d("test", "not null drawable");
        }

        return drawable;
    }

    public void dismiss() {
        dialog.dismiss();
    }
}
